package smartKiwi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;

import javax.swing.JOptionPane;

import net.sf.jcarrierpigeon.WindowPosition;
import net.sf.jtelegraph.Telegraph;
import net.sf.jtelegraph.TelegraphType;

import org.apache.commons.codec.binary.Base64;
import org.java_websocket.WebSocket;
import org.java_websocket.WebSocketImpl;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

/**
 * A simple WebSocketServer implementation. Keeps track of a "chatroom".
 */
public class SmartKiwiServer extends WebSocketServer {
	private SmartKiwi sk;

	public SmartKiwiServer( int port , SmartKiwi _sk) throws UnknownHostException {
		super( new InetSocketAddress( port ) );
		sk = _sk;
	}

	public SmartKiwiServer( InetSocketAddress address ,SmartKiwi _sk) {
		super( address );
		sk = _sk;
	}

	@Override
	public void onOpen( WebSocket conn, ClientHandshake handshake ) {

	}

	@Override
	public void onClose( WebSocket conn, int code, String reason, boolean remote ) {

	}

	@Override
	public void onMessage( WebSocket conn, String message ) {
		System.out.println(message);
		int returnCode = -1;
		SmartKiwiRequest req = new SmartKiwiRequest(sk.getProps());
		if (message.startsWith("SENDDOCUMENT")) {
			try {
				
				//Get value of forceFiche (false if not specified)
				String forceFiche = message.split(" ")[message.split(" ").length-1];
				String ficheId = "";
				String dossierId = "";
				String b64Content = "";
				String fileName = "";
				if(forceFiche.equals("true"))
				{
					//AFFICHE IHM FORCE FICHE
				}
				
				//Get content in B64 from file path
				String strPath = message.substring(message.indexOf("\"")+1, message.lastIndexOf("\""));
				Path path = Paths.get(strPath);
				byte[] data = Files.readAllBytes(path);
				b64Content = new Base64().encodeToString(data);
				fileName = path.toFile().getName();

				//BUILD THE JSON OBJECT
				String jsonObject = "{\"ficheId\":\""+ficheId+"\",\"dossierId\":\""+dossierId+"\",\"content\":\""+b64Content+"\",\"fileName\":\""+fileName+"\"}";
				JOptionPane.showMessageDialog(null, jsonObject);
				//req.envoyerDocument(jsonObject);
				if (returnCode == -1) { 
					Telegraph telegraph = new Telegraph("Request result",
							"Connection failed", TelegraphType.NOTIFICATION_ERROR,
							WindowPosition.BOTTOMRIGHT, 4000);
					telegraph.animate();
				} else if (returnCode == 0 || returnCode == 1) { 
					
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} else if (message.startsWith("SENDTEXT")) {
			
			//Get value of forceFiche (false if not specified)
			String forceFiche = message.split(" ")[message.split(" ").length-1];
			String ficheId = "";
			String dossierId = "";
			String content = "";
			if(forceFiche.equals("true"))
			{
				//AFFICHE IHM FORCE FICHE
			}
			
			//Get content in B64 from file path
			content = message.substring(message.indexOf("\"")+1, message.lastIndexOf("\""));

			//BUILD THE JSON OBJECT
			String jsonObject = "{\"ficheId\":\""+ficheId+"\",\"dossierId\":\""+dossierId+"\",\"content\":\""+content+"\"}";
			JOptionPane.showMessageDialog(null, jsonObject);
			//req.envoyerTexte(jsonObject);
			
			if (returnCode == -1) { 
				Telegraph telegraph = new Telegraph("Request result",
						"Connection failed", TelegraphType.NOTIFICATION_ERROR,
						WindowPosition.BOTTOMRIGHT, 4000);
				telegraph.animate();
			} else if (returnCode == 0 || returnCode == 1) { 
				
			}
		} else {
			Telegraph telegraph = new Telegraph("Request result",
					"Unknown Request", TelegraphType.NOTIFICATION_ERROR,
					WindowPosition.BOTTOMRIGHT, 4000);
			telegraph.animate();
		}
	}

	public static void main( String[] args ) throws InterruptedException , IOException {
		WebSocketImpl.DEBUG = true;
		int port = 8082; // 843 flash policy port
		try {
			port = Integer.parseInt( args[ 0 ] );
		} catch ( Exception ex ) {
		}
		SmartKiwi sk = new SmartKiwi();
		SmartKiwiServer s = new SmartKiwiServer( port, sk);
		s.start();
		System.out.println( "SmartKiwiService started on port: " + s.getPort() );
	}
	@Override
	public void onError( WebSocket conn, Exception ex ) {
		ex.printStackTrace();
		if( conn != null ) {
			// some errors like port binding failed may not be assignable to a specific websocket
		}
	}

	/**
	 * Sends <var>text</var> to all currently connected WebSocket clients.
	 * 
	 * @param text
	 *            The String to send across the network.
	 * @throws InterruptedException
	 *             When socket related I/O errors occur.
	 */
	public void sendToAll( String text ) {
		Collection<WebSocket> con = connections();
		synchronized ( con ) {
			for( WebSocket c : con ) {
				c.send( text );
			}
		}
	}
}
